<template>
  <a-card :title="$t('selected') + ' ' + this.selectedRows.length + ' ' + $t('room')">
    <template #extra>
      <a-space>
        <a-button type="primary" icon="plus" @click="showForm(null)">{{ $t('add') }}{{ $t('room') }}
        </a-button>
        <a-popconfirm :title='$t("are_you_sure")' ok-text="Yes" okType="danger" cancel-text="No"
                      @confirm="deleteRoom()" :disabled="!deleteSelectedRows">
          <a-icon slot="icon" type="question-circle-o" style="color: red"/>
          <a-button type="danger" :loading="submitLoading" :disabled="!deleteSelectedRows">
            {{ $t("delete") }}{{ $t('room') }}
          </a-button>
        </a-popconfirm>
        <a-popconfirm :title='$t("are_you_sure")' ok-text="Yes" okType="danger" cancel-text="No"
                      @confirm="recoveryRoom()" :disabled="!recoverySelectedRows">
          <a-icon slot="icon" type="question-circle-o" style="color: red"/>
          <a-button :loading="submitLoading" :disabled="!recoverySelectedRows">
            {{ $t("recovery") }}{{ $t('room') }}
          </a-button>
        </a-popconfirm>
        <a-button icon="reload" @click="getData()" :loading="loading">
        </a-button>
      </a-space>
    </template>
    <a-table :bordered="false" size="small" :columns="columns" :data-source="roomList"
             :row-key="record => record.roomId"
             :loading="loading" :pagination="false" :row-selection="rowSelection">
      <template slot="roomId" slot-scope="text, record">
        <a @click="showForm(record)">{{ record.roomId }}</a>
      </template>
      <template slot="roomNameEn" slot-scope="text, record">
        {{ record.roomNameEn }} <br/> {{ record.roomNameCn }}
      </template>
      <template slot="bed" slot-scope="text, record">
        <room-beds :bed-list="record.roomBeds"/>
      </template>
      <a-icon slot="status" slot-scope="text" :type="text?'check-circle':'close-circle'"
              :style="text?'color:#52c41a;font-size: 18px;':'font-size: 18px;'"/>
      <template v-for="(item, index) in columns" :slot="item.slotName">
        <span :key="index">{{ $t(item.slotName) }}</span>
      </template>
    </a-table>

    <a-modal v-model="editVisible" :maskClosable="false" :title="editTitle" :confirm-loading="confirmLoading"
             :okText="$t('submit')" @ok="saveForm()" @cancel="closeForm()" width="60%">
      <a-form-model ref="updateForm" layout="vertical" :model="updateForm" autocomplete="off" :rules="updateFormRules">
        <a-row :gutter="[16,0]" justify="center">
          <a-col :span="12">
            <a-form-model-item prop="roomNameEn" :label="$t('room_name') + 'EN'">
              <a-input v-model="updateForm.roomNameEn">
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item prop="roomNameCn" :label="$t('room_name') + 'CN'">
              <a-input v-model="updateForm.roomNameCn">
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item prop="roomArea" :label="$t('room_area')">
              <a-input v-model="updateForm.roomArea">
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item prop="maxOccupancy" :label="$t('max_occupancy')">
              <a-input-number v-model="updateForm.maxOccupancy">
              </a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-button type="primary" icon="plus" @click="showBedForm()">{{ $t('set') }}{{ $t('bed') }}
            </a-button>
          </a-col>
          <a-col :span="20">
            <a-tag v-for="(item,index) in updateForm.roomBeds" :key="index" :closable="true" @close="closeTag(index)">
              <a v-if="updateForm.roomBeds.length > 1 && index > 0"> {{ $t('or') }} </a>
              <span v-for="(bed,j) in item" :key="j">
                {{ bed.num }} {{ bed.type }}{{ bed.width > 0 ? "(" + bed.width + "m)" : "" }} <a v-if="item.length > 1 && j < item.length - 1"> {{ $t('and') }} </a>
              </span>
            </a-tag>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>

    <a-modal v-model="selectBedVisible" :maskClosable="false" :title="$t('bed')" :okText="$t('confirm')"
             @ok="confirmBedForm()" @cancel="closeBedForm()">
      <a-form :form="bedForm" layout="inline">
        <a-row :gutter="[16,0]" justify="center">
          <a-col :span="10">
            {{ $t('bed') }}
          </a-col>
          <a-col :span="7">
            {{ $t('number_of_beds') }}
          </a-col>
          <a-col :span="7">
            {{ $t('bed_width') }}
          </a-col>
        </a-row>
        <a-row v-for="(item,index) in defaultBeds" :key="index" :gutter="[16,-16]" justify="center">
          <a-col :span="10">
            <a-form-item>
              <a-checkbox v-decorator="[`types[${index}]`]" :checked="bedsChecked[index]"
                          @change="onBedChange($event,index)">{{
                  item.type.charAt(0).toUpperCase() + item.type.slice(1)
                }}
              </a-checkbox>
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item>
              <a-input-number v-decorator="[`nums[${index}]`,{initialValue:item.num}]" style="width: 100%">
              </a-input-number>
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item>
              <a-input-number v-decorator="[`widths[${index}]`]" style="width: 100%">
              </a-input-number>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

  </a-card>
</template>

<script>
import {getRoomList, deleteRooms, restoreRooms, updateRoom} from '@/services/hotel'
import RoomBeds from './roombeds'

export default {
  name: "RoomList",
  props: ['HotelId'],
  components: {RoomBeds},
  i18n: require('../i18n'),
  data() {
    return {
      loading: false,
      submitLoading: false,
      roomList: [],
      defaultBeds: [],
      bedsChecked: [],
      bedFormData: [],
      bedForm: this.$form.createForm(this, {name: 'bedForm'}),
      columns: [
        {
          dataIndex: 'roomId',
          align: 'center',
          slotName: "room_id",
          slots: {title: 'room_id'},
          scopedSlots: {customRender: 'roomId'},
        },
        {
          dataIndex: 'roomNameEn',
          align: 'left',
          slotName: "room_name",
          slots: {title: 'room_name'},
          scopedSlots: {customRender: 'roomNameEn'},
          sorter: (a, b) => a.roomNameEn.localeCompare(b.roomNameEn),
        }, {
          dataIndex: 'maxOccupancy',
          align: 'center',
          slotName: "max_occupancy",
          slots: {title: 'max_occupancy'},
        },
        {
          dataIndex: 'roomArea',
          align: 'center',
          slotName: "room_area",
          slots: {title: 'room_area'},
          sorter: (a, b) => parseInt(a.roomArea) - parseInt(b.roomArea),
        }, {
          dataIndex: 'roomBeds',
          align: 'left',
          slotName: "bed",
          slots: {title: 'bed'},
          scopedSlots: {customRender: 'bed'},
        },
        {
          dataIndex: 'roomStatus',
          align: 'center',
          slotName: "status",
          slots: {title: 'status'},
          scopedSlots: {customRender: 'status'},
        },
        {
          dataIndex: 'updatedByName',
          align: 'center',
          slotName: "updatedByName",
          slots: {title: 'updatedByName'},
        }, {
          dataIndex: 'updatedTime',
          align: 'center',
          slotName: "updatedTime",
          slots: {title: 'updatedTime'},
        }, {
          dataIndex: 'thirdPartyId',
          align: 'left',
          slotName: "third_party_id",
          slots: {title: 'third_party_id'},
        },
      ],
      selectedRows: [],
      deleteSelectedRows: false,
      recoverySelectedRows: false,
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRows = selectedRows
          this.deleteSelectedRows = false
          this.recoverySelectedRows = false
          this.selectedRows.forEach(item => {
            if (item.roomStatus) {
              this.deleteSelectedRows = true
              this.recoverySelectedRows = false
            }else {
              this.recoverySelectedRows = true
              this.deleteSelectedRows = false
            }
          })
        }
      },
      updateForm: {},
      editVisible: false,
      editTitle: '',
      confirmLoading: false,
      updateFormRules: {
        roomNameEn: [{required: true, trigger: 'blur',message:' '}],
        roomNameCn: [{required: true, trigger: 'blur',message:' '}],
        roomArea: [{required: false, trigger: 'blur',message:' '}],
        maxOccupancy: [{required: true, trigger: 'blur',message:' '}],
      },
      selectBedVisible: false,
    }
  },
  methods: {
    getData() {
      this.loading = true
      getRoomList(this.$props.HotelId).then(res => {
        const {roomList, defaultBeds} = res.data.data
        this.roomList = roomList
        this.defaultBeds = defaultBeds
        for (let i = 0; i < this.defaultBeds.length; i++) {
          this.bedsChecked.push(false)
        }
        this.loading = false
      }).catch(error => {
        console.log(error)
      })
    },
    deleteRoom() {
      if (this.selectedRows.length == 0) {
        this.$message.error(this.$t('no_item_selected'))
        return
      }
      this.submitLoading = true
      let roomIds = []
      this.selectedRows.forEach(row => {
        roomIds.push(row.roomId)
      })
      deleteRooms(roomIds).then(res => {
        if (res.data.success) {
          this.$message.success({content: this.$t('deleteSuccess')})
          this.getData()
          this.submitLoading = false
        } else {
          this.$message.error({content: this.$t(res.data.message)})
        }
      }).catch(error => {
        console.log(error)
      })
    },
    recoveryRoom() {
      if (this.selectedRows.length == 0) {
        this.$message.error(this.$t('no_item_selected'))
        return
      }
      this.submitLoading = true
      let roomIds = []
      this.selectedRows.forEach(row => {
        roomIds.push(row.roomId)
      })
      restoreRooms(roomIds).then(res => {
        if (res.data.success) {
          this.$message.success({content: this.$t('recoverySuccess')})
          this.getData()
          this.submitLoading = false
        } else {
          this.$message.error({content: this.$t(res.data.message)})
        }
      }).catch(error => {
        console.log(error)
      })
    },
    showForm(record) {
      if (record === null) {
        this.editTitle = this.$t('add') + this.$t('room')
        this.updateForm = { hotelId: this.$props.HotelId, roomStatus: true, roomBeds: []}
      } else {
        this.editTitle = this.$t('edit') + this.$t('room')
        this.updateForm = JSON.parse(JSON.stringify(record))
        this.editReadonly = true
      }
      this.editVisible = true
    },
    saveForm() {
      this.$refs.updateForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true

          let newBedList = []
          this.updateForm.roomBeds.forEach(item => {
            if(item !== null)
              newBedList.push(item)
          })
          this.updateForm.roomBeds = newBedList
          updateRoom(this.updateForm).then(res => {
            if (res.data.success) {
              this.$message.success({content: this.$t('submitSuccess')})
              this.closeForm()
              this.getData()
            } else {
              this.$message.error({content: this.$t(res.data.message)})
            }
          }).catch(error => {
            console.log(error)
          })

        } else {
          return false;
        }
      });
    },
    closeForm() {
      this.confirmLoading = false
      this.editVisible = false
      this.updateForm = {}
      this.$refs.updateForm.clearValidate()
    },
    showBedForm() {
      this.selectBedVisible = true
    },
    confirmBedForm() {
      this.bedForm.validateFields((err, values) => {
        if (!err) {
          console.log(values)
          if (this.updateForm.roomBeds === undefined)
            this.updateForm.roomBeds = []

          const {types, nums, widths} = values
          let beds = []
          for (let i = 0; i < this.defaultBeds.length; i++) {
            if (types[i])
              beds.push({type: this.defaultBeds[i].type, num: nums[i], width: widths[i] ? widths[i] : 0})
          }
          if (beds.length > 0)
            this.updateForm.roomBeds.push(beds)

          console.log(this.updateForm.roomBeds)
          this.closeBedForm()
        }
      });
    },
    closeBedForm() {
      this.selectBedVisible = false
      for (let i = 0; i < this.defaultBeds.length; i++) {
        this.bedsChecked[i] = false
      }
      this.bedForm.resetFields()
    },
    onBedChange(e, index) {
      this.bedsChecked[index] = e.target.checked
    },
    closeTag(index) {
      //this.$delete(this.updateForm.roomBeds,index)
      //this.$props.BedList.splice(index,1)
      delete this.updateForm.roomBeds[index]
      console.log(this.updateForm.roomBeds)
    },
  },
  created() {
    this.getData()
  }
}
</script>